﻿using System;
using System.Data;
using System.Configuration;
using System.Collections;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Web.UI.HtmlControls;
using System.Drawing;
using System.IO;

namespace FutureMeWeb
{
    public partial class validate : System.Web.UI.Page
    {
        //产生验证码
        public string CreateCode(int codeLength)
        {
            char[] chArray;
            chArray = "23456789AaBbCcDdEeFfGgHhiJjKkMmNnPpQqRSsTtUuVvWwXxYyZz".ToCharArray();
            Random random = new Random();
            string checkCode = string.Empty;
            for (int i = 0; i < codeLength; i++)
            {
                checkCode += chArray[random.Next(0, chArray.Length)].ToString();
            }
            return checkCode;
        }
        //产生验证图片
        private void CreateImage(string checkCode)
        {
            int numLength;
            numLength = checkCode.Length * 0x10;
            Bitmap image = new Bitmap(numLength, 0x18
                );
            Graphics graphics = Graphics.FromImage(image);
            graphics.Clear(Color.White);
            Color[] colorArray2 = new Color[] { Color.Black, Color.Red, Color.DarkBlue, Color.Green, Color.Chocolate, Color.Brown, Color.DarkCyan, Color.Purple };
            string[] strArray2 = new string[] { "Verdana", "Microsoft Sans Serif", "Comic Sans MS", "Arial" };
            Random random = new Random();

            //画图片的背景噪音线
            for (int i = 0; i < 50; i++)
            {
                int x = random.Next(image.Width);
                int y = random.Next(image.Height);
                graphics.DrawRectangle(new Pen(Color.LightGray, 0f), x, y, 1, 1);
            }
            for (int j = 0; j < checkCode.Length; j++)
            {
                int index = random.Next(7);
                int num7 = random.Next(4);
                Font font = new Font(strArray2[num7], 12f, FontStyle.Bold);
                Brush brush = new SolidBrush(colorArray2[index]);
                graphics.DrawString(checkCode.Substring(j, 1), font, brush, (float)(1 + (j * 14)), 1f);
            }
            graphics.DrawRectangle(new Pen(Color.Black, 0f), 0, 0, image.Width - 1, image.Height - 1);
            MemoryStream stream = new MemoryStream();
            image.Save(stream, System.Drawing.Imaging.ImageFormat.Jpeg);
            base.Response.ClearContent();
            base.Response.ContentType = "image/Jpeg";
            base.Response.BinaryWrite(stream.ToArray());
            graphics.Dispose();
            image.Dispose();
        }

        protected void Page_Load(object sender, EventArgs e)
        {
            string checkCode = CreateCode(4);
            this.Session["validate_code"] = checkCode;
            this.CreateImage(checkCode);
        }
    }
}